/*
 * @(#) BuildProgramRegistrationDAOImpl.java
 * Copyright (c) 2011 EdRP, Dayalbagh Educational Institute.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * Redistributions of source code must retain the above copyright
 * notice, this  list of conditions and the following disclaimer.
 *
 * Redistribution in binary form must reproducuce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL ETRG OR ITS CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributors: Members of EdRP, Dayalbagh Educational Institute
 */
package in.ac.dei.edrp.cms.daoimpl.programregistration;

import in.ac.dei.edrp.cms.common.utility.MyException;
import in.ac.dei.edrp.cms.common.utility.ProogramRegistrationDate;
import in.ac.dei.edrp.cms.dao.programregistration.BuildProgramRegistrationDAO;
import in.ac.dei.edrp.cms.domain.programregistration.ProgramRegistrationDetails;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.sqlmap.client.SqlMapExecutor;

/**
 * Creation date: 10-Feb-2011
 * This class implements those methods that is used for program registration.
 * @author <a href="http://aniltiwaripms.blogspot.com" target="_blank">Anil Kumar Tiwari</a>
 * @version 1.0
 */

public class BuildProgramRegistrationDAOImpl extends SqlMapClientDaoSupport implements BuildProgramRegistrationDAO{

	static final Logger logger = Logger.getLogger(BuildProgramRegistrationDAOImpl.class);
	
	/** 
	 * Method getSessionDate is used for getting the session date of an university.
	 * @param universityId
	 * @return List of the ProgramRegistrationDetails.
	 * @see in.ac.dei.edrp.cms.domain.programregistration.ProgramRegistrationDetails
	 */
	
	public ProgramRegistrationDetails getSessionDate(String universityId)throws DataAccessException {
		ProgramRegistrationDetails sessionDate = null;
		try{
			sessionDate = (ProgramRegistrationDetails) getSqlMapClientTemplate().queryForObject("ProgramRegistration.getSessionDate",universityId);
		}catch(DataAccessException dae){
			throw new MyException("Session date does not found");
		}
		return sessionDate;
	}

	/**
	 * Method insertProgramRegistration is used for inserting the data.
	 * @param registrationPeriod
	 * @param addDropPeriod
	 * @param sessionStartDate
	 * @param sessionEndDate
	 * @param universityId
	 * @throws ParseException
	 */
	@SuppressWarnings("unchecked")
	
	public List<Integer> insertProgramRegistration(final int registrationPeriod, final int addDropPeriod,
			final String sessionStartDate,final String sessionEndDate,final String universityId,final String userId) throws ParseException {

		return	(List<Integer>) getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
		         public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
		        	int numberOfRecordsInserted = 0;	
		        	int recordsInLogs = 0;
		        	List<Integer> insertionInfo = new ArrayList<Integer>();
		        	try{
			    			String[] sessionYearMonth = sessionStartDate.split("-");
			    			int sessionYear = Integer.parseInt(sessionYearMonth[0]);
			    			int sessionMonth = Integer.parseInt(sessionYearMonth[1]);
			    			List<ProgramRegistrationDetails> programRegDetailList = getSqlMapClientTemplate().queryForList("ProgramRegistration.getSemesterDate");
			        		insertionInfo.add(programRegDetailList.size());
			        		Iterator<ProgramRegistrationDetails> programRegDetailIterator = programRegDetailList.iterator();
			        		executor.startBatch();
			           		while(programRegDetailIterator.hasNext()){
			           			ProgramRegistrationDetails programDetails = programRegDetailIterator.next();
			           			ProgramRegistrationDetails programRegistrationDetails =
			           				ProogramRegistrationDate.getProgramRegistrationObject(programDetails,
			           						sessionMonth,sessionYear,registrationPeriod,
			           						addDropPeriod,sessionStartDate,
			           						sessionEndDate,userId,universityId,"-");
			        			ProgramRegistrationDetails desiredProgramCourseKey = 
			        				(ProgramRegistrationDetails) getSqlMapClientTemplate().queryForObject("ProgramRegistration.checkExistance",programRegistrationDetails);
			        			if(desiredProgramCourseKey==null){
			        					executor.insert("ProgramRegistration.insertProgramRegistrationDetail", programRegistrationDetails);
			        			}
			        			else{
			        				logger.info("this record already exist and key="+programRegistrationDetails.getProgramCourseKey()
			        						+" ,semStartDate="+programRegistrationDetails.getSemesterStartDate()+
			        						" ,semEndDate="+programRegistrationDetails.getSemesterEndDate()+
			        						", sessionStartDate="+programRegistrationDetails.getSessionStartDate()+
			        						", sessionEndDate="+programRegistrationDetails.getSessionEndDate()+
			        						", status="+programRegistrationDetails.getStatus());
			        				recordsInLogs++;
			        			}
		        			}
			           		insertionInfo.add(recordsInLogs);
			           		numberOfRecordsInserted = executor.executeBatch();
			           		insertionInfo.add(numberOfRecordsInserted);
			           }catch(Exception e){
			        		//executor.executeBatch();
			        		e.printStackTrace();
			        		logger.error("error in insertProgramRegistration="+e);
			        		throw new MyException("problem in insertion of program registration");
						} 
			        	return insertionInfo;
			         }
					});
			}

	/** 
	 * Method getProgramRegistrationDetails is used for getting all program details which
	 * are not inserted.
	 * @see in.ac.dei.edrp.cms.domain.programregistration.ProgramRegistrationDetails
	 */
	@SuppressWarnings("unchecked")
	
	public List<ProgramRegistrationDetails> getProgramRegistrationDetails(ProgramRegistrationDetails sessionDate) throws DataAccessException {
		List<ProgramRegistrationDetails> programDetails = null;
		try{
			programDetails = getSqlMapClientTemplate().queryForList("ProgramRegistration.getProgramRegistrationDetail",sessionDate);

		}catch(DataAccessException dae){
			System.out.println(dae);
			throw new MyException("program details does not found");
		}
		return programDetails;
	}
	
	/**
	 * Method insertSingleProgramRegistration is used for inserting single record
	 * @param programDetails
	 * @param registrationPeriod
	 * @param addDropPeriod
	 * @param sessionStartDate
	 * @param sessionEndDate
	 * @param universityId
	 * @param userId
	 * @throws ParseException
	 */
	public void insertSingleProgramRegistration(ProgramRegistrationDetails programDetails,
			int registrationPeriod,int addDropPeriod,String sessionStartDate,
			String sessionEndDate,String universityId,String userId) throws ParseException,DataAccessException{		
		String[] sessionYearMonth = sessionStartDate.split("-");
		int sessionYear = Integer.parseInt(sessionYearMonth[0]);
		int sessionMonth = Integer.parseInt(sessionYearMonth[1]);
		try{
		ProgramRegistrationDetails programRegistrationDetails =
				ProogramRegistrationDate.getProgramRegistrationObject(programDetails,
						sessionMonth,sessionYear,registrationPeriod,
						addDropPeriod,sessionStartDate,
						sessionEndDate,userId,universityId,"-");		
			getSqlMapClientTemplate().insert("ProgramRegistration.insertProgramRegistrationDetail", programRegistrationDetails);
		}catch(DataAccessException dae){
			throw new MyException("Single program could not be inserted.");
		}
		
	}

	@SuppressWarnings("unchecked")
	public String systemBuildRegistration(ProgramRegistrationDetails sessionDate) {
		try{
			List<ProgramRegistrationDetails> details = getSqlMapClientTemplate().queryForList("ProgramRegistration.checkProgramRegistration", sessionDate);
			System.out.println(details.size());
			if(details.size()==0)
			{
				getSqlMapClientTemplate().insert("ProgramRegistration.systemBuildProgramRegistration",sessionDate);				
				getSqlMapClientTemplate().insert("ProgramRegistration.systemUpdatePreviousRegistration",sessionDate);
			}
			else return "alreadyExist";
		}
		catch(DataAccessException dae)
		{
			throw new MyException("Problem in registering for new session");
		}
		return "success";
	}

	

}
